<?php
	
	namespace App\Http\Controllers\Admin;
	
	use App\Http\Controllers\Controller;
	use DB;
	
	class ZksController extends Controller
	{
		private $iniOrder = [['addr','hb6303'], ['users', 'client'], ['stations'], ['contract', 'expire', 'tester'], ['stationPcShare'], ['vcr']];
		private $orderKey;
		
		public function __construct()
		{
			$this->orderKey = domain() . 'ZksOrder';
			// cache()->forget($this->orderKey);
		}
		
		public function setOrder()
		{
			$order = cache($this->orderKey, $this->iniOrder);
			$chag = 0;
			if ($postOrder = request('order', '')) {
				foreach ($order as $k1 => $val1) {
					foreach ($val1 as $k2 => $val2) {
						if ($val2 == $postOrder[0]) {
							$chag += 1;
							$order[$k1][$k2] = $postOrder[1];
						}
						if ($val2 == $postOrder[1]) {
							$chag += 1;
							$order[$k1][$k2] = $postOrder[0];
						}
						if ($chag === 2) {
							break;
						}
					}
				}
				cache([$this->orderKey => $order], 99999);
			}
			return 1;
		}
		
		public function index()
		{
			$data = $this->getContent();
			$order = cache($this->orderKey, $this->iniOrder);
			//排序
			$data['order'] = $order;

			//获取用户当前的地址
			$data['addr'] = [];
			if (config('constant.is_lan')) {
				$data['addr'] = [];
			}else{
				// $data['addr'] = curl("http://api.map.baidu.com/location/ip?ak=dELXcqGX0714b9wv6H8f5wsLRyC0mVUN&ip=" . request()->getClientIp() . "&coor=bd09ll");
			}
			//温湿度大气压计
			$data['hb6303'] = $this->getEnvInfo();
			//录像机
			$content = DB::table('a_vcr')
						->where('ishide', 0)
						->where('lan_ip', '!=', '')
						->where('server_lan_ip', '!=', '')
						->select('name', 'lan_ip', 'server_lan_ip', 'channel_count','username','password')
						->get();
			$data['vcr'] = ['title' => '录像机', 'toMid' => true, 'key' => 'vcr', 'content' => $content];
			$zksTitle = DB::table('setting_sys')->where('key','zks_title')->value('value') ?: '保定汇邦安全工器具检测中控平台';
			// dd($data,$zksTitle);
			return view('admin.zks.index', compact('data','zksTitle'));
		}
			
		//管理员
		public function manager($id)
		{
			$data = DB::table('manager')->find($id);
			$roleIds = explode(',', $data->role_ids ?: $data->role_id);
			$roleNames = DB::table('role')->whereIn('id', $roleIds)->pluck('role_name')->toArray();
			$data->role_names = implode(',', $roleNames);
			return view('admin.zks.manager', compact('data'));
		}
		
		//客户
		public function client($id)
		{
			$data = DB::table('a_client')->find($id);
			return view('admin.zks.client', compact('data'));
		}
		
		//批次
		public function contract($id)
		{
			$data = DB::table('a_contract_gaiyao as a')->leftJoin('a_contract as b', 'a.contract_id', '=', 'b.id')->where('b.id', $id)->get();
			return view('admin.zks.contract', compact('data'));
		}
		
		//到期
		public function expire($clientName)
		{
			$seting = getCache('setting');
			$nexttimelimit = date('Y-m-d', strtotime('+' . unserialize($seting['warn_days_limit'])['days'] . ' days'));
			$nextMintimelimit = date('Y-m-d', strtotime('-15 days'));
			$data = DB::table('a_sample_info as a')
					->leftJoin('a_contract as b', 'a.contract_id', '=', 'b.id')
					->leftJoin('a_contract_gaiyao as c', 'a.contract_gaiyao_id', '=', 'c.id')
					->where('b.client_name', '=', $clientName)
					->whereDate('a.next_time', '>', $nextMintimelimit)
					->whereDate('a.next_time', '<', $nexttimelimit)
					->where('a.res', 1)->where('a.notice', 1)
					->select('a.bar_code', 'a.contract_id', 'a.contract_gaiyao_id', 'a.next_time', 'a.gqj_ID', 'b.client_name', 'c.tool_name')
					->get();   //樣品信息
			return view('admin.zks.expire', compact('data'));
		}
		
		//设备
		public function station($id)
		{
			$data = DB::table('a_station')->find($id);
			$dbStat = StationController::dbStat();
			foreach ($dbStat as $col => $value) {
				$data->$col = $value[$data->$col];
			}
			return view('admin.zks.station', compact('data'));
		}
		
		//今日主检工作量
		public function tester($id)
		{
			$dbStat = ItemDataController::dbStat();
			$date = date('Y-m-d');
			$data = DB::table('a_item_data as a')->leftJoin('manager as b', 'b.id', '=', 'a.manager_id')->leftJoin('a_sample_info as c', 'a.sample_info_id', '=', 'c.id')->leftJoin('a_testitem as d', 'a.item_id', '=', 'd.id')->leftJoin('a_contract_gaiyao as e', 'a.contract_gaiyao_id', '=', 'e.id')->where('a.manager_id', $id)->whereDate('a.utime', $date)->selectRaw('b.realname,c.bar_code,d.name as item_name,a.res,a.commit,e.tool_name')->orderBy('a.utime', 'desc')->get();
			return view('admin.zks.tester', compact('data', 'dbStat'));
		}

		//录像机
		public function vcr($lanip)
		{
			$info = DB::table('a_vcr')->where('lan_ip',$lanip)->first();
			return view('admin.zks.vcr', compact('info'));
		}

		//温湿度大气压设备详情
		public function hb6303($id){
			$info = DB::table('a_hb6303 as a')
						->leftJoin('a_env_info as b','a.id','=','b.hb6303_id')
						->where('a.id',$id)
						->select('a.*','b.temp','b.humi','b.pressure')
						->orderBy('b.id','desc')
						->first();
			switch($info->type){
				case 'temp_hum':
					$stations = DB::table('a_station')->where('temp_hum_num',$info->dev_num)->get();
					break;
				case 'press':
					$stations = DB::table('a_station')->where('press_num',$info->dev_num)->get();
					break;
				default:
					$stations = DB::table('a_station')->where('temp_hum_num',$info->dev_num)->orWhere('press_num',$info->dev_num)->get();
			}
			return view('admin.zks.hb6303', compact('stations', 'info'));
		}

		//获取最近数据
		public function getContent(){
			$data = [];
			//用户
			$data['users'] = ['title' => '管理员', 'toMid' => false, 'key' => 'user', 'url' => 'user', 'content' => DB::table('manager')->where('id', '>', '1')->select('id', 'realname as val1', 'username as val2', 'chizheng as val3')->get()];
			
			
			//客户信息
			$data['client'] = ['title' => '客户列表', 'toMid' => true, 'key' => 'client', 'url' => 'client', 'column' => ['NO', '送检单位', '联系人', '联系电话', '创建时间'], 'content' => DB::table('a_client')->select('id', 'name as val1', 'contact as val2', 'telephone as val3', 'created_at as val4')->get(),];
			
			//在受理批次
			$content = DB::table('a_contract')->where([['is_del', '=', 0], ['status', '!=', 20]])->select('id', 'batchNum as val1', 'status as val2', 'client_name as val3', 'creator as val4')->orderBy('id', 'desc')->get();
			$dbStat = \App\Admin\Contract::dbStat();
			foreach ($content as $k => $value) {
				$content[$k]->val2 = $dbStat['status'][$value->val2];
			}
			$data['contract'] = ['title' => '在受理批次', 'toMid' => true, 'key' => 'contract', 'url' => 'contract', 'column' => ['NO', '批次号', '状态', '送检单位', '受理人'], 'content' => $content];
			
			//到期预警
			$seting = getCache('setting');
			$nexttimelimit = date('Y-m-d', strtotime('+' . unserialize($seting['warn_days_limit'])['days'] . ' days'));
			$nextMintimelimit = date('Y-m-d', strtotime('-15 days'));
			$content = DB::table('a_sample_info as a')
					->leftJoin('a_contract as b', 'a.contract_id', '=', 'b.id')
					->whereDate('a.next_time', '<', $nexttimelimit)
					->whereDate('a.next_time', '>', $nextMintimelimit)
					->where('a.notice', 1)
					->where('a.res', 1)
					->select(DB::raw('b.client_name AS id,b.client_name AS val1,COUNT(1) AS val2'))
					->groupBy('b.client_name')->get();
			$client = DB::table('a_client')->select('name', 'contact', 'telephone')->get()->keyBy('name');
			foreach ($content as $k => $item) {
				$content[$k]->val3 = isset($client[$item->val1]) ? $client[$item->val1]->contact : '';
				$content[$k]->val4 = isset($client[$item->val1]) ? $client[$item->val1]->telephone : '';
			}
			$data['expire'] = ['title' => '到期预警', 'toMid' => true, 'key' => 'expire', 'url' => 'expire', 'column' => ['NO', '送检单位', '数量', '联系人', '联系电话'], 'content' => $content];
			// dd($data['expire']);
			//检测设备（工位）
			$stations = DB::table('a_station')->where('ishide',0)->where('status', '<', 4)->orderBy('dev_num', 'asc')->get();
			$dbStat = StationController::dbStat();
			$content = [];
			$pcsharestations = [];
			foreach ($stations as $item) {
				$valAry = ['id' => $item->id, 'val1' => $item->name, 'val2' => $dbStat['status'][$item->status], 'val3' => $item->dev_num, 'val4' => $item->user,];
				array_push($content, (object)$valAry);
				if ($item->com_lan_ip) {
					$pcsharestations[] = $item;
				}
			}
			$data['stations'] = ['title' => '检测设备', 'toMid' => true, 'key' => 'stations', 'url' => 'station', 'column' => ['NO', '设备名称', '状态', '设备编号', '负责人'], 'content' => $content];
			
			//工位屏幕共享监控
			$data['stationPcShare'] = ['title' => '工位显示器', 'toMid' => true, 'key' => 'stationPcShare', 'content' => $pcsharestations];
			
			//主捡人
			$date = date('Y-m-d');
			$testers = DB::table('manager')->where('status', '2')->where('istester', 1)->select('num', 'realname', 'partner')->get()->keyBy('realname');
			$content = DB::table('a_item_data as a')
						->leftJoin('manager as b', 'b.id', '=', 'a.manager_id')
						->where('b.status', '2')
						->where('b.istester', 1)
						->whereDate('a.utime', $date)
						->selectRaw('b.id,b.realname as val1,COUNT(1) as val2')
						->groupBy('b.id')->get();
			foreach ($content as $item) {
				$relname = $item->val1;
				$item->val3 = $testers[$relname]->num;
				$item->val4 = $testers[$relname]->partner;
			}
			$data['tester'] = ['title' => '今日主检', 'toMid' => true, 'url' => 'tester', 'key' => 'tester', 'column' => ['NO', '姓名', '项目完成量', '工号', '副检'], 'content' => $content];
			return $data;
		}

		// 温湿度大气压计
		public function getEnvInfo(){
			$sql = "SELECT
                    a.*,c.*
                FROM
                    `a_hb6303` AS `a`
                LEFT JOIN (
                    SELECT
                        max(id) as env_id,
                        dev_num
                    FROM
                        a_env_info
                    GROUP BY
                        dev_num
                ) AS `b` ON `a`.`dev_num` = `b`.`dev_num`
                LEFT JOIN (
                    SELECT
                        id as c_id,temp,humi,pressure,time as last_time
                    FROM
                        a_env_info
                ) AS `c` ON `c`.`c_id` = `b`.`env_id` ";
	        $hb6303 = DB::select($sql);
			return $hb6303;
		}
	}
